package com.zywl.utils.utils.weixin;

import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

/**
 * 公众平台通用接口工具类
 * 
 */
public class WeixinUtil {
	private static Logger logger = Logger.getLogger(WeixinUtil.class.getName());	

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param outputStr 提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	private static final int HTTP_CONNECTION_TIMEOUT = 60 * 1000;
	private static final int HTTP_READ_TIMEOUT = 60 * 1000;
	public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager()  };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(HTTP_CONNECTION_TIMEOUT);
			httpUrlConn.setReadTimeout(HTTP_READ_TIMEOUT);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
//			logger.error("Weixin server connection timed out.");
		} catch (Exception e) {
//			logger.error("https request error:{}", e);
		}
		return jsonObject;
	}
	
	
	// 菜单创建（POST） 限100（次/天）
	public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

	/**
	 * 创建菜单
	 * 
	 * @param menu 菜单实例
	 * @param accessToken 有效的access_token
	 * @return 0表示成功，其他值表示失败
	 */
	public static int createMenu(Menu menu, String accessToken) {
		int result = 0;

		// 拼装创建菜单的url
		String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);
		// 将菜单对象转换成json字符串
		String jsonMenu = JSONObject.fromObject(menu).toString();
		// 调用接口创建菜单
		JSONObject jsonObject = httpRequest(url, "POST", jsonMenu);

		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				logger.error(String.format("创建菜单失败 errcode:{%s} errmsg:{%s}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")));
			}
		}

		return result;
	}
	
	
	// 获取access_token的接口地址（GET） 限200（次/天）
	public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

	/**
	 * 获取access_token
	 * 
	 * @param appid 凭证
	 * @param appsecret 密钥
	 * @return
	 */
	public static AccessToken getAccessToken(String appid, String appsecret) {
		AccessToken accessToken = null;
		try{
			String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
			JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
//            String str = HttpClientUtil.doGet(requestUrl);
//            JSONObject jsonObject = JSONObject.fromObject(str);
			// 如果请求成功
			if (null != jsonObject) {
				try {
					accessToken = new AccessToken();
					accessToken.setToken(jsonObject.getString("access_token"));
					accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
				} catch (Exception e) {
					accessToken = null;
					// 获取token失败
					logger.error(String.format("获取token失败 errcode:{%s} errmsg:{%s}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")));
				}
			}
		}catch (Exception e) {
			return accessToken;
		}
		return accessToken;
	}
	
	// 菜单删除（GET） 限100（次/天）
	public final static String menu_delete_url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
	/**
	 * 删除菜单
	 * 
	 * @param accessToken 有效的access_token
	 * @return 0表示成功，其他值表示失败
	 */
	public static int deleteMenu(String accessToken) {
		int result = 0;

		// 拼装创建菜单的url
		String url = menu_delete_url.replace("ACCESS_TOKEN", accessToken);
		// 调用接口删除菜单
		JSONObject jsonObject = httpRequest(url, "GET",null);

		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				logger.error(String.format("删除菜单失败 errcode:{%s} errmsg:{%s}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")));
			}
		}

		return result;
	}
	
	
	
	// 获取授权access_token的接口地址（GET） 限200（次/天）
	public final static String oauth2_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

	/**
	 * 获取access_token
	 * 
	 * @param appid 凭证
	 * @param appsecret 密钥
	 * @param code 
	 * @return
	 */
	public static Oauth2AccessToken getOauth2AccessToken(String appid, String appsecret, String code) {
		Oauth2AccessToken accessToken = null;

		String requestUrl = oauth2_access_token_url.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				accessToken = new Oauth2AccessToken();
				accessToken.setToken(jsonObject.getString("access_token"));
				accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
				accessToken.setRefresh_token(jsonObject.getString("refresh_token"));
				accessToken.setOpenid(jsonObject.getString("openid"));
				accessToken.setScope(jsonObject.getString("scope"));
				logger.info(String.format("获取网页授权token {%s} ", jsonObject.toString()));
			} catch (Exception e) {
				accessToken = null;
				// 获取token失败
				logger.error(String.format("获取token失败 errcode:{%s} errmsg:{%s}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")));
			}
		}
		return accessToken;
	}
	
	
	// 消息模板发送信息
	public static String template_send_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

	/**
	 * 消息模板发送信息
	 * 
	 * @param 
	 * @param 
	 * @return 
	 */
	public static int TemplateSend(String accessToken,String info) {
		int result = 0;

		// 消息模板发送信息的url
		String url = template_send_url.replace("ACCESS_TOKEN", accessToken);
//		JSONObject json = new JSONObject();
//		json.put("touser", "oEjHbjpGodV5PLQJTmUmGOF6-Lbs");
//		json.put("template_id", "DpkgFra0hbO8SpcjqCMvxb377zoN5nnftbiOtJia1M8");
//		json.put("url", "");
//		json.put("topcolor", "#FF0000");
//		
//		JSONObject ja = new JSONObject();
//
//		JSONObject ja1 = new JSONObject();
//		ja1.put("value", "你好");
//		ja1.put("color", "#173177");
//		ja.put("first",ja1.toString());
//		
//		ja1 = new JSONObject();
//		ja1.put("value", "张三");
//		ja1.put("color", "#173177");
//		ja.put("childName",ja1.toString());
//
//		ja1 = new JSONObject();
//		ja1.put("value", "2014年11月24日");
//		ja1.put("color", "#173177");
//		ja.put("time",ja1.toString());
//		
//		ja1 = new JSONObject();
//		ja1.put("value", "已到校");
//		ja1.put("color", "#173177");
//		ja.put("status",ja1.toString());
//		
//		ja1 = new JSONObject();
//		ja1.put("value", "感谢你的阅读！");
//		ja1.put("color", "#173177");
//		ja.put("remark",ja1.toString());
//		
//		
//		json.put("data", ja);
		// 调用消息模板接口发送信息
		JSONObject jsonObject = httpRequest(url, "POST",info);

		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
			}
			logger.error(String.format("json :{%s}", jsonObject.toString()));
		}
		
		return result;
	}

	public final static String get_user_phone_number_url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN";
	/**
	 * 获取access_token
	 * @return
	 */
	public static String getuserphonenumber(String code, String accessToken) {
		String  phone = null;
		try{
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("code", code);
			String requestUrl = get_user_phone_number_url.replace("ACCESS_TOKEN", accessToken);
			JSONObject jo = httpRequest(requestUrl, "GET", jsonObject.toString());
			// 如果请求成功
			if (null != jo) {
				try {
					phone = jsonObject.getString("phone_info");
				} catch (Exception e) {
					// 获取手机号码失败
					logger.error(String.format("获取phone_info失败 errcode:{%s} errmsg:{%s}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")));
				}
			}
		}catch (Exception e) {
			return phone;
		}
		return phone;
	}
}
